import 'dart:typed_data';

import 'package:activity_record/model/data_base.dart';
import 'package:activity_record/model/diy_project.dart';
import 'package:activity_record/pages/diy_add_dialog.dart';
import 'package:activity_record/pages/diy_analysis.dart';
import 'package:activity_record/pages/diy_item_info.dart';
import 'package:activity_record/pages/diy_search.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';

/*
这是首页，包含标题栏、底部导航栏和浮动按钮
因为
 */

class HomePage extends StatefulWidget {
  @override
  HomePageState createState() => new HomePageState();
}

class HomePageState extends State<HomePage> {
  final _title = '活动展示'; //appBar标题,前置下划线表示该成员变量类内可见
  //实例化数据库对象
  var _database = new DataBase();
  //实例化diyProjects数组，并初始化空
  List<DiyProject> _diyProjects = <DiyProject>[];
  //实例化没有结款的diyProject数组，同样初始化空
  List<DiyProject> _unCheckedDiyProjects = <DiyProject>[];

  //遍历数据库初始化_diyProjects数据
  _getDiyProjects() async {
    print('=========开始读取数据库全部数据=========');
    List result = await _database.getDiyProjects();
    _diyProjects.clear();
    setState(() {
      if (result.length != 0) {
        result.forEach((diy) => _diyProjects.add(DiyProject.fromMap(diy)));
      } else
        _diyProjects = [];
    });
  }

  //遍历数据库未结账的_diyProjects数据
  _getUnCheckedDiyProjects() async {
    print('=========开始读取数据库没有结账的数据=========');
    List result = await _database.getUnCheckedDiyProjects();
    _unCheckedDiyProjects.clear();
    setState(() {
      if (result.length != 0) {
        result.forEach(
            (diy) => _unCheckedDiyProjects.add(DiyProject.fromMap(diy)));
      } else
        _unCheckedDiyProjects = [];
    });
  }

  //数据初始化
  @override
  void initState() {
    super.initState();
    _getDiyProjects();
    _getUnCheckedDiyProjects();
  }

  //进入新增页面
  Future _addDiyProject() async {
    await Navigator.of(context).push(
      new MaterialPageRoute(
        fullscreenDialog: true,
        builder: (context) {
          return new DiyAddDialog(db: _database);
        },
      ),
    );
    _getDiyProjects();
    _getUnCheckedDiyProjects();
  }

  //点击卡片右上角删除按钮后从数据库删除diyProject
  Future _deleteDiyProject(DiyProject diyProject, int index) async {
    await _database.deleteDiyProject(diyProject.id);
    //从当前项目数组中移除该项目，并通知系统重绘
    setState(() {
      _diyProjects.removeAt(index);
    });
    _getUnCheckedDiyProjects();
  }

  //标记已结算方法进行数据库更新
  _markChecked(DiyProject diyProject, int index) async {
    await _database.updateChecked(diyProject);
    var result = await _database.getDiyProject(diyProject.id);
    setState(() {
      _diyProjects.removeAt(index);
      _diyProjects.insert(index, result);
    });
    _getUnCheckedDiyProjects();
  }

  //根据拼接的图片字符串拆分成对应的uint8list数组
  Uint8List _getUint8List(String imagePath) {
    List p = [];
    if (imagePath.contains('&')) {
      List x = imagePath.split('&');
      x.forEach((value) {
        List y = value.split('-');
        List<int> z = [];
        y.forEach((string) {
          z.add(int.parse(string));
        });
        p.add(Uint8List.fromList(z));
      });
      return p.first;
    } else {
      List y = imagePath.split('-');
      List<int> z = [];
      y.forEach((string) {
        z.add(int.parse(string));
      });
      p.add(Uint8List.fromList(z));
      return p.first;
    }
  }

  @override
  Widget build(BuildContext context) {
    //使用默认的tab控制器来实现tab标签和展示内容的联动
    return new DefaultTabController(
      //length代表一共有几个tabbar
      length: 2,
      child: new Scaffold(
        //标题栏，包含一个标题和一个图标按钮
        appBar: new AppBar(
          elevation: 1.0,
          title: new Text('活动展示'),
          centerTitle: true,
          //TabBar是属于appbar的底部属性控件
          bottom: new PreferredSize(
            preferredSize: new Size(0.0, 20.0),
            child: new TabBar(
              indicatorColor: Colors.white,
              // labelColor: Color(0xff813066),
              // unselectedLabelColor: Colors.grey[600],
              indicatorSize: TabBarIndicatorSize.label,
              tabs: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(bottom: 4.0),
                  child: new Text(
                    '全部(${_diyProjects.length})',
                    // style: Theme.of(context)
                    //     .textTheme
                    //     .body1,
                  ),
                ),
                new Text(
                  '未结(${_unCheckedDiyProjects.length})',
                  // style: Theme.of(context)
                  //     .textTheme
                  //     .body1
                  //     .copyWith(color: Colors.grey[600]),
                ),
              ],
            ),
          ),
        ),
        //TabBarView用于展示对应tab标签下的内容，通过默认的tab控制器来实现对应
        body: new TabBarView(
          children: <Widget>[
            new Container(
              color: Colors.grey[100],
              child: _diyProjects.length == 0
                  ? new Center(child: new Text('尝试新增一条记录吧'))
                  : new ListView.builder(
                      itemCount: _diyProjects.length,
                      itemBuilder: (context, index) {
                        return new Card(
                          margin: const EdgeInsets.fromLTRB(
                              15.0, 15.0, 15.0, 6.0), //设置外边距18
                          //card形状设置顶部圆形弧度12，底部没有
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8.0)),
                          //inkwell是一个带水波纹触摸效果的控件，预留点击回调作为以后点击响应事件
                          child: new InkWell(
                            onTap: () {
                              Navigator.of(context).push(new MaterialPageRoute(
                                  builder: (BuildContext context) {
                                return new DiyItemInfo(
                                  diyProject: _diyProjects[index],
                                  db: _database,
                                  diyProjects: _diyProjects,
                                  unCheckedDiyProjects: _unCheckedDiyProjects,
                                );
                              }));
                            },
                            child: _diyContentShow(
                                context, _diyProjects[index], index),
                          ),
                        );
                      },
                    ),
            ),
            new Container(
              color: Colors.grey[100],
              child: _unCheckedDiyProjects.length == 0
                  ? new Center(child: new Text('所有活动都已结款'))
                  : new ListView.builder(
                      itemCount: _unCheckedDiyProjects.length,
                      itemBuilder: (context, index) {
                        return new Card(
                          margin: const EdgeInsets.fromLTRB(
                              18.0, 18.0, 18.0, 9.0), //设置外边距18
                          //card形状设置顶部圆形弧度12，底部没有
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.vertical(
                                  top: Radius.circular(12.0))),
                          //inkwell是一个带水波纹触摸效果的控件，预留点击回调作为以后点击响应事件
                          child: new InkWell(
                            onTap: () {
                              Navigator.of(context).push(new MaterialPageRoute(
                                  builder: (BuildContext context) {
                                return new DiyItemInfo(
                                  diyProject: _unCheckedDiyProjects[index],
                                  db: _database,
                                  diyProjects: _unCheckedDiyProjects,
                                  unCheckedDiyProjects: _unCheckedDiyProjects,
                                );
                              }));
                            },
                            child: _diyContentShow(
                                context, _unCheckedDiyProjects[index], index),
                          ),
                        );
                      },
                    ),
            ),
          ],
        ),
        floatingActionButton: new FloatingActionButton(
          onPressed: () {
            _addDiyProject();
          },
          child: new Icon(Icons.add),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        bottomNavigationBar: new BottomAppBar(
          shape: CircularNotchedRectangle(),
          child: Row(
            //将横布局下的子控件按照头尾的方式摆放
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              new IconButton(
                icon: new Icon(Icons.search),
                onPressed: () {
                  Navigator.of(context).push(new MaterialPageRoute(
                      fullscreenDialog: true,
                      builder: (context) {
                        return new DiySearch(
                          db: _database,
                        );
                      }));
                },
              ),
              new IconButton(
                icon: new Icon(Icons.format_line_spacing),
                onPressed: () {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (context) {
                    return new DiyDataAnalysis(
                      db: _database,
                    );
                  }));
                },
              )
            ],
          ),
        ),
      ),
    );
  }

  //点击项目右上角按钮底部弹窗
  _showBottomSheet(DiyProject diyProject, int indexSelected) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return new Container(
            height: 180.0,
            child: new Column(
              children: <Widget>[
                new ListTile(
                  leading: new Icon(Icons.delete),
                  title: new Text('删除'),
                  onTap: () {
                    Navigator.of(context).pop();
                    _alertDialgIsDelete(diyProject, indexSelected);
                  },
                ),
                new ListTile(
                  leading: !diyProject.isPaided
                      ? Icon(Icons.done_all)
                      : Icon(Icons.cancel),
                  title: !diyProject.isPaided
                      ? new Text('标记已结算')
                      : new Text('标记未结算'),
                  onTap: () {
                    Navigator.of(context).pop();
                    _markChecked(diyProject, indexSelected);
                  },
                ),
                new ListTile(
                  leading: new Icon(Icons.alarm),
                  title: new Text('设置收款提醒'),
                ),
              ],
            ),
          );
        });
  }

  //弹窗对话框确认是否删除
  _alertDialgIsDelete(DiyProject diyProject, int indexSelected) {
    showDialog(
      context: context,
      builder: (context) {
        return Theme.of(context).platform == TargetPlatform.iOS
            ? new CupertinoAlertDialog(
                title: new Text('是否确认删除?'),
                content: new Text('此次操作无法挽回，你将彻底失去我'),
                actions: <Widget>[
                  new CupertinoDialogAction(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: new Text('再想想')),
                  new CupertinoDialogAction(
                    onPressed: () {
                      _deleteDiyProject(diyProject, indexSelected);
                      Navigator.pop(context);
                    },
                    child: new Text(
                      '不要了',
                      style: new TextStyle(color: Colors.red),
                    ),
                  ),
                ],
              )
            : new AlertDialog(
                title: new Text('是否确认删除?'),
                actions: <Widget>[
                  new FlatButton(
                    child: new Text('取消'),
                    onPressed: () => Navigator.pop(context),
                  ),
                  new FlatButton(
                    child: new Text('确定'),
                    onPressed: () {
                      _deleteDiyProject(diyProject, indexSelected);
                      Navigator.pop(context);
                    },
                  )
                ],
              );
      },
    );
  }

//card第一行时间和预留按钮菜单
  Widget _rowTime(DiyProject diyProject, int indexSelected) {
    return new Container(
      //设置距离左边8.0的内间距
      padding: const EdgeInsets.fromLTRB(5.0,4.0,5.0,4.0),
      child: new Row(
        //表示两个子空间头尾分布
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          new Row(children: <Widget>[
            diyProject.isPaided == true
                ? new Icon(
                    Icons.mood,
                    color: Colors.indigoAccent,
                  )
                : new Icon(
                    Icons.mood_bad,
                    color: Color(0xffdd2c00),
                  ),
            new SizedBox(
              width: 5.0,
            ),
            new Text(diyProject.date),
          ]),
          new InkWell(
            child: new Icon(
              Icons.more_horiz,
              color: Colors.grey,
            ),
            onTap: () {
              _showBottomSheet(diyProject, indexSelected);
            },
          )
        ],
      ),
    );
  }

//card第三行名称和地点
  Widget _rowNameAndPlace(DiyProject diyProject) {
    return new Container(
      padding: const EdgeInsets.all(8.0),
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          new Text(diyProject.name,
              style:
                  new TextStyle(fontSize: 17.0, fontWeight: FontWeight.bold)),
          Row(
            children: <Widget>[
              new Icon(Icons.place, size: 16.0),
              new Text(diyProject.place),
            ],
          ),
        ],
      ),
    );
  }

//进行card里的内容组合
  Widget _diyContentShow(
      BuildContext context, DiyProject diyProject, int indexSelected) {
    return Container(
      height: 288.0,
      child: new Column(
        children: <Widget>[
          _rowTime(diyProject, indexSelected),
          //使用expanded将填充控件的剩余空间
          new Expanded(
              //flex代表这个控件在父控件里的范围比例，默认是1，这里表示在高度288的容器里，图片会填满剩余的所有空间
              flex: 3,
              child: new Image.memory(
                _getUint8List(diyProject.imagePath),
                fit: BoxFit.cover,
                width: MediaQuery.of(context).size.width,
              )),
          _rowNameAndPlace(diyProject),
          new Padding(
            padding: const EdgeInsets.fromLTRB(8.0, 0.0, 8.0, 8.0),
            child: new Row(
              children: <Widget>[
                new Text(
                  '${diyProject.singlePrcie.toString()}元',
                  style: new TextStyle(
                      fontSize: 15.0,
                      color: Theme.of(context).primaryColor,
                      fontWeight: FontWeight.bold),
                ),
                new SizedBox(
                  width: 20.0,
                ),
                new Text(
                  '${diyProject.nums.toString()}份',
                  style: new TextStyle(
                      fontSize: 15.0,
                      color: Theme.of(context).primaryColor,
                      fontWeight: FontWeight.bold),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
